from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render, redirect
from elasticsearch import Elasticsearch
import time
import json
from django.http import HttpResponse
from django.db import connection
from redis import StrictRedis
from django.core.cache import cache
import os
from django.conf import settings

redis = StrictRedis(host='121.4.140.74', port=2333, db=0, password='snbzsyc', decode_responses=True)


def home(request):
    ip = request.META["REMOTE_ADDR"]
    if redis.get(ip) is not None:
        user = redis.get(ip)
        path = "/static/images/face30.png"
        sql = "SELECT `icon` FROM `user` WHERE `name` = '{0}'".format(user)
        with connection.cursor() as cursor:
            cursor.execute(sql)
            data = cursor.fetchone()
            if len(data) != 0:
                try:
                    path = "/static/upload/" + data[0]
                except:
                    pass
        return render(request, 'index2.html', {"user": user,
                                               "path": path})
    return render(request, 'index2.html', {"user": "no",
                                           "path": "/static/images/face30.png"})


def changeip(request):
    request.encoding = 'utf-8'
    if 'ip' in request.POST and request.POST['ip']:
        ip = request.POST['ip']
    else:
        ip = "192.168.0.1"
    return redirect("/index/?ip=" + ip)


def getList(request):
    print(request.META)
    print(request)
    return render(request, "index.html")

def pending(request):
    init = time.time() * 1000
    start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    ip = request.META.get("REMOTE_ADDR")
    rds = StrictRedis(host='121.4.140.74', port=2333, db=1, password='snbzsyc', decode_responses=True)
    count = rds.get(ip)
    if count:
        count = int(count) + 1
        rds.set(ip, count)
        print(ip + " count + 1")
        if count > 4:
            return HttpResponse('403', status=403)
    else:
        rds.set(ip, 1)
        print(ip + " start")
    time.sleep(10)
    end = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    used = round(time.time() * 1000 - init, 2)
    count = rds.get(ip)
    if count:
        count = int(count) - 1
        if count == 0:
            rds.delete(ip)
            print(ip + " delete")
        else:
            print(ip + " count -1")
            rds.set(ip, count)
    return render(request, "index.html", {"start": start,
                                          "end": end,
                                          "timeused": used})

def insertEs(request):
    es = Elasticsearch([{'host': '121.4.140.74', 'port': 9200}], timeout=3600)
    mappings = {
        "mappings": {
            "properties": {
                "id": {
                    "type": "long",
                    "index": True
                },
                "status": {
                    "type": "long",
                    "index": True
                },
                "@timestamp": {
                    "type": "long",
                    "index": True
                }
            }
        }
    }
    # res = es.indices.create(index='type_doc_test', body=mappings)
    ip = request.META["REMOTE_ADDR"]
    action = {
        "ip": ip,
        "status": "200",
        "uri": "insert",
        "@timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
    }
    resp = es.index(index="index_test", doc_type="doc_type_test", body=action)
    # print("RES1:", res)
    print("RES2:", resp)


def mysqlinsertTest(request):
    with connection.cursor() as cursor:
        cursor.execute("SELECT VERSION()")
        data = cursor.fetchone()
    response = HttpResponse(json.dumps(data))
    response["Access-Control-Allow-Origin"] = "*"
    return response


def ajaxtest(request):
    data = {"abc": 1,
            "cba": 2}
    response = HttpResponse(json.dumps(data))
    response["Access-Control-Allow-Origin"] = "*"
    return response


def pageinit(request):
    page = int(request.GET.get("page"))
    sql = "SELECT `article`.*, `user`.icon FROM `article` LEFT JOIN `user` ON `article`.auther = `user`.`name` ORDER BY id DESC limit " + str(page * 5) + ",5 "
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()
    response = HttpResponse(json.dumps(data))
    response["Access-Control-Allow-Origin"] = "*"
    return response


def getpage(request):
    sql = "SELECT COUNT(*) FROM `article`"
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchone()
    response = HttpResponse(data)
    response["Access-Control-Allow-Origin"] = "*"
    return response


def addgood(request):
    id = request.GET.get("id")
    good = request.GET.get("good")
    sql = "UPDATE `article` set `good` = " + good + " where `id` = " + id
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()
    response = HttpResponse(json.dumps(data))
    response["Access-Control-Allow-Origin"] = "*"
    return response


def getcomment(request):
    id = request.GET.get("id")
    sql = "SELECT `comment`.*, `user`.icon FROM `comment` LEFT JOIN `user` ON `comment`.applyer = `user`.`name` where `art_id` = " + id
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()
    response = HttpResponse(json.dumps(data))
    response["Access-Control-Allow-Origin"] = "*"
    return response


def addcomment(request):
    artid = request.POST["artid"]
    username = request.POST["username"]
    comment = request.POST["comment"]
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    sql = "INSERT INTO `comment`(`art_id`, `content`, `applyer`, `timestamp`) VALUES ({0}, '{1}', '{2}', '{3}')".format(
        artid, comment, username, timestamp)
    sql2 = "UPDATE `article` set `coments` = coments+1 where `id` = " + artid
    with connection.cursor() as cursor:
        cursor.execute(sql)
        cursor.execute(sql2)
    response = HttpResponse("success")
    response["Access-Control-Allow-Origin"] = "*"
    return response


def login(request):
    username = request.POST["name"]
    password = request.POST["password"]
    ip = request.META["REMOTE_ADDR"]
    sql = "SELECT password from `user` where `name` = '{}' ".format(username)
    with connection.cursor() as cursor:
        cursor.execute(sql)
        data = cursor.fetchall()

    res = "success"
    if len(data) == 0:
        res = "no user"
    else:
        for item in data:
            if item[0] != password:
                res = "pswd wrong"
        if res == "success":
            redis.set(ip, username)
    response = HttpResponse(res)
    response["Access-Control-Allow-Origin"] = "*"
    return response


def regist(request):
    username = request.POST["name"]
    password = request.POST["password"]
    ip = request.META["REMOTE_ADDR"]
    if "张" in username and "研" in username:
        response = HttpResponse("zy")
        response["Access-Control-Allow-Origin"] = "*"
        return response
    res = "success"
    if redis.get("ip") is not None:
        res = redis.get("ip")
    else:
        sql0 = "SELECT name from `user` where `name` = '{}' ".format(username)
        with connection.cursor() as cursor:
            cursor.execute(sql0)
            data = cursor.fetchall()
        if len(data) != 0:
            res = "user exist"
        else:
            sql = "INSERT INTO `webdemo`.`user`(`name`, `phone`, `password`) VALUES ('{0}', 188, '{1}')".format(
                username, password)
            with connection.cursor() as cursor:
                cursor.execute(sql)
            redis.set(ip, username)
    response = HttpResponse(res)
    response["Access-Control-Allow-Origin"] = "*"
    return response


def alert(request):
    alertinfo = str(request.body, encoding="utf-8")
    ip = alertinfo.split("alertstart")[1].split(",\"title")[0].split(":")[0].strip()[5:].replace("/", "").strip()
    if ip:
        black_list = cache.get("blackList", [])
        black_list.append(ip)
        cache.set("blackList", black_list, timeout=60 * 60 * 24)


        # blacklist = list(redis.lrange("black", 0, -1))
        # if ip not in blacklist:
        #     redis.rpush("black", ip)
        #
        #     blacklist = list(redis.lrange("black", 0, -1))
        #
        # es = Elasticsearch([{'host': '121.4.140.74', 'port': 9200}], timeout=3600)
        sql = "INSERT INTO `alert` (`message`, `time`) VALUES ('{0}', '{1}')".format(
            ip, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        with connection.cursor() as cursor:
            cursor.execute(sql)
    # query = {
    #     "size": 0,
    #     "query": {
    #         "range": {
    #             "@timestamp": {
    #                 "gte": "now-10s",
    #                 "lt": "now"
    #             }
    #         }
    #     },
    #     "aggs": {
    #         "terms_count": {
    #             "terms": {
    #                 "field": "remote_addr_agg"
    #             }
    #         }
    #     }
    # }
    # res = es.search(index="logstash-nginx", body=query)
    # for item in res["aggregations"]["terms_count"]["buckets"]:
    #     if item["doc_count"] > 10:
    #         redis.rpush("black", item["key"])
    #         sql = "INSERT INTO `alert` (`message`) VALUES ('{0}')".format(
    #             item["key"] + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    #         with connection.cursor() as cursor:
    #             cursor.execute(sql)

    response = HttpResponse("success")
    response["Access-Control-Allow-Origin"] = "*"
    return response


def publish(request):
    username = request.POST["name"]
    text = request.POST["text"]
    title = request.POST["title"]
    sql = "INSERT INTO `article`(`auther`, `title`, `content`, `good`, `coments`, `timestamp`) VALUES ('{0}', '{1}', '{2}', 0, 0, '{3}')".format(
        username, title, text, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    with connection.cursor() as cursor:
        cursor.execute(sql)

    response = HttpResponse("success")
    response["Access-Control-Allow-Origin"] = "*"
    return response

def upload(request):
    user = request.GET["user"]
    files = request.FILES.getlist("file", None)  # 接收前端传递过来的多个文件
    for file in files:
        if int(file.size) > 51200:
            return HttpResponse('403', status=403)
        sql_path = f"/home/web/weblog/static/upload/{file.name}"
        # 写入文件
        with open(sql_path, 'wb') as f:
            for content in file.chunks():
                f.write(content)

        sql = "UPDATE `user` SET `icon` = '{0}' WHERE `name` = '{1}'".format(file.name, user)
        with connection.cursor() as cursor:
            cursor.execute(sql)

    response = HttpResponse("200")
    response["Access-Control-Allow-Origin"] = "*"
    return response

def clearcache(request):
    cache.set("blackList", [], timeout=60 * 60 * 24)
    response = HttpResponse("200")
    response["Access-Control-Allow-Origin"] = "*"
    return response
